package com.doit.day02;

import com.alibaba.fastjson.JSON;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.*;

public class Exercise_Consumer {

    public static void main(String[] args) {
       HashSet<Integer> set = new HashSet<>();//用bitmap

       //开启这个线程
       new Thread(new ConsumerTask(set)).start();

        //设置一个定时器
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("截止到"+System.currentTimeMillis()+"为止，他的uv是："+set.size());
            }
        },10000,5000);

    }
}

class ConsumerTask implements Runnable{
    private HashSet<Integer> set;
    private KafkaConsumer<String, String> consumer;
    //构造方法
    public ConsumerTask(HashSet<Integer> set){
        //创建消费者对象
        Properties props = new Properties();
        props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"linux01:9092");
        props.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.GROUP_ID_CONFIG,"g003");
        props.setProperty(ConsumerConfig.ALLOW_AUTO_CREATE_TOPICS_CONFIG,"true");
        props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
        props.setProperty(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,"true");
        props.setProperty(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG,"3000");
        consumer = new KafkaConsumer<String, String>(props);
        this.set = set;
    }

    @Override
    public void run() {
        //订阅主题
        consumer.subscribe(Arrays.asList("eventlog"));
        while (true){
            //拉取数据
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofMillis(Integer.MAX_VALUE));
            for (ConsumerRecord<String, String> record : poll) {
                String json = record.value();
                //把他转成EventLog对象  怎么转
                EventLog eventLog = JSON.parseObject(json, EventLog.class);
                //获取到guid
                Integer guid = eventLog.getGuid();
                set.add(guid);
            }
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


